package com.ww.juc.completable.future.async;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * supplyAsync
 * supplyAsync是创建带有返回值的异步任务，它有如下两个方法，一个是使用默认线程池（ForkJoinPool.commonPool()）的方法，一个是带有自定义线程池的重载方法
 * @author wanggw
 * 2024年2月4日 下午4:26:12
 */
public class SupplyAsyncDemo {

	/**
	 * // 带返回值异步请求，默认线程池
	 * public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
	 * // 带返回值的异步请求，可以自定义线程池
	 * public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// 使用默认线程池
		CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
			System.out.println("异步可以做你想做的事情...");
			return "这是返还的结果";
		});
		
		System.out.println("回到主线程打印执行结果：" + cf1.get());
		
		System.out.println("--------------------------------------");
		
		// 自定义线程池
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
			System.out.println("异步执行你想做的任何事...");
			
			return "这是异步执行返还的结果";
		}, executorService);
		
		System.out.println("主线程来打印你的战果吧：" + cf2.get());

		executorService.shutdown();
	}
}
